<?php


namespace App\Repositories;


use Carbon\Carbon;
use App\Common\ProductData;
use App\Exceptions\BasicException;

class RewardRepository
{
    public function addReward($reward, $rewardDetails)
    {
        $newReward = app('model_reward')->create($reward);
        if ($newReward) {
            foreach ($rewardDetails as $rewardDetail) {
                $rewardDetail['reward_id'] = $newReward['id'];
                $this->upRewardDetail($rewardDetail);
            }

            return;
        }
        throw new BasicException(98001);
    }

    public function upReward($reward, $rewardDetails)
    {
        $where = [];
        $where[] = ['id', '=', $reward['id']];
        $where[] = ['active', '=', 1];
        $oldReward = app('model_reward')->where($where)->first();
        if ($oldReward) {
            $whereDetail[] = ['reward_id', '=', $oldReward['id']];
            app('model_reward_detail')->where($whereDetail)->delete();
            app('model_reward')->where($where)->update($reward);
            if ($rewardDetails) {
                foreach ($rewardDetails as $rewardDetail) {
                    $rewardDetail['reward_id'] = $reward['id'];
                    $this->upRewardDetail($rewardDetail);
                }
            }
        }
    }

    public function upRewardDetail($rewardDetail)
    {
        $rewardDetail['add_time'] = Carbon::now()->timestamp;
        app('model_reward_detail')->create($rewardDetail);
    }

    public function delReward($reward)
    {
        $where = [];
        $where[] = ['id', '=', $reward['id']];
        $where[] = ['active', '=', 1];
        $reward['active'] = 2;
        $oldReward = app('model_reward')->where($where)->update($reward);
        if ($oldReward) {
            return;
        }
        throw new BasicException(98001);
    }

    public function getRewardList($where, $page, $perPage)
    {
        $where[] = ['active', '=', 1];
        $rewardList = app('model_reward')
            ->with([
                'reward_detail' => function ($query) {
                    $query->select('id', 'reward_id', 'item_id', 'number', 'weight',
                        'type');//->with(['reward_item:id,name,type'])
                },
            ])
            ->where($where)
            ->orderBy('id', 'desc')
            ->paginate($perPage, ['*'], '', $page);
        foreach ($rewardList->items() as $value) {
            foreach ($value->reward_detail as $item) {
                $rewarItem = ProductData::getProductData($item->type, $item->item_id);
                $item->reward_item = $rewarItem;
            }
        }
        if ($rewardList) {
            return $rewardList;
        }
        throw new BasicException(98002);
    }

    //发送奖励
    public function sendReward($user_id, $reward_id)
    {
        $reward = app('model_reward')->with([
            'reward_detail' => function ($query) {
                $query->with('reward_item');
            },
        ])->where('id', $reward_id)->first();
        if (!$reward || !$reward->reward_detail) {
            return false;
        }
        $remark = '打开'.$reward->name.'礼包获得';
        if ($reward->type == 2) {//特殊道具包,根据权重获取随机道具
            $reward_details = $this->getRandRewardDetail($reward);
        } else {
            $reward_details = $reward->reward_detail;
        }
        foreach ($reward_details as $reward_detail) {
            $this->sendRewardDetail($user_id, $reward_detail, $remark);
        }
    }

    //根据权重获取道具中具体的奖励
    public function getRandRewardDetail($reward)
    {
        $all_weight = 0;
        $reward_details = [];
        foreach ($reward->reward_detail as $key => &$value) {
            if ($value->weight == 9999) {
                $reward_details[] = $value;
                $reward->reward_detail->forget($key);
                continue;
            } else {
                $all_weight += $value->weight;
            }
        }
        foreach ($reward->reward_detail as $reward_detail) {
            $randNum = mt_rand(1, $all_weight);
            if ($randNum <= $reward_detail->weight) {
                $reward_details[] = $reward_detail;

                return $reward_details;
            } else {
                $all_weight -= $reward_detail->weight;
            }
        }
    }

    public function sendRewardDetail($user_id, $reward_detail, $remark = '')
    {
        $type = $reward_detail->type;
        if ($type == 8) {
            $reward_detail->reward_item->number = $reward_detail->number;
            return $this->sendRewardItemDetail($user_id, $reward_detail->reward_item, $remark);
        }

        $id = $reward_detail->item_id;
        $number = $reward_detail->number;
        $type = $reward_detail->type;
        $product_id = $reward_detail->item_id;

        switch ($type) {
            case 1://赠送积分
                $this->sendScore($user_id, $number, $id, $remark);
                break;
            case 2://赠送个性商品-头像框
            case 3://赠送个性商品-坐骑
            case 4://赠送个性商品-入场特效
            case 12://赠送个性商品-道具
                $this->sendDress($user_id, $product_id, $number);
                break;
            case 5://赠送金币
                $this->sendGold($user_id, $number, $id, $remark);
                break;
            case 6://赠送礼物
                $this->sendGift($user_id, $product_id, $number);
                break;
            default:
                return [];
        }
    }

    public function sendRewardItemDetail($user_id, $reward_item, $remark = '')
    {
        $id = $reward_item->id;
        $number = $reward_item->number;
        $type = $reward_item->type;
        $product_id = $reward_item->product_id;
        switch ($type) {
            case 1://赠送积分
                $this->sendScore($user_id, $number, $id, $remark);
                break;
            case 2://赠送个性商品-头像框
            case 3://赠送个性商品-坐骑
            case 4://赠送个性商品-入场特效
            case 12://赠送个性商品-道具
                $this->sendDress($user_id, $product_id, $number);
                break;
            case 5://赠送金币
                $this->sendGold($user_id, $number, $id, $remark);
                break;
            case 6://赠送礼物
                $this->sendGift($user_id, $product_id, $number);
                break;
            case 7://魔法帽
            case 8://碎片1
            case 9://碎片2
            case 10://碎片3
            case 11://碎片4
                $this->sendProp($user_id, $number, $type);
                break;
        }
    }

    public function sendProp($user_id, $number, $type)
    {
        $user_prop = app('model_user_prop')->getUserProp($user_id);
        if ($type == 7) {
            $field = 'magic_hat';
            $log_type = 1;
        } elseif ($type == 8) {
            $field = 'chip1';
            $log_type = 2;
        } elseif ($type == 9) {
            $field = 'chip2';
            $log_type = 3;
        } elseif ($type == 10) {
            $field = 'chip3';
            $log_type = 4;
        } else {
            $field = 'chip4';
            $log_type = 5;
        }
        $user_prop->increment($field, $number);
        app('model_user_prop_log')->create([
            'user_id' => $user_id,
            'type'    => $log_type,
            'number'  => $number,
        ]);
    }

    //赠送积分
    public function sendScore($user_id, $number, $foreign_id = 0, $remark = '')
    {
        app('repo_user_score')->sendScore($user_id, $number, 1, $foreign_id, $remark);
    }

    //赠送个性商品
    public function sendDress($user_id, $product_id, $number)
    {
        app('model_mall_orders')->give($product_id, $user_id, $number);
    }

    //赠送金币
    public function sendGold($user_id, $number, $foreign_id = 0, $remark = '')
    {
        $update_money_result = app('repo_user')->updateUserMoney(
            [
                'user_id' => $user_id,
                'money'   => $number,
            ]
        );
        if (!$update_money_result) {
            throw new BasicException(41005);
        }

        //记录资金日志
        app('model_account_log')->addLog($user_id, $number, $remark, 55, $foreign_id);
    }

    //赠送礼物(到背包)
    public function sendGift($user_id, $gift_id, $number)
    {
        app('model_gift_backpack')->sendBackpackGift($user_id, $gift_id, $number);
    }

    //type:1道具包2道具
    public function getRewardDetail($id, $type, $number = 1)
    {
        if (isset($this->mall_products)) {
            $mall_products = $this->mall_products;
        } else {
            $mall_products = app('model_mall_products')->get()->keyBy('id');
            $this->mall_products = $mall_products;
        }
        if (isset($this->all_gift)) {
            $all_gift = $this->all_gift;
        } else {
            $all_gift = app('model_gift')->get()->keyBy('id');
            $this->all_gift = $all_gift;
        }
        if (isset($this->all_reward_item)) {
            $all_reward_item = $this->all_reward_item;
        } else {
            $all_reward_item = app('model_reward_item')->get()->keyBy('id');
            $this->all_reward_item = $all_reward_item;
        }
        if ($type == 1) {
            $detail = app('model_reward')->where('id', $id)->with('reward_detail')->first();
            if (!isset($detail->reward_detail) || empty($detail->reward_detail)) {
                return [];
            }
            $detail->number = $detail->number > 0 ? $detail->number : 1;
            $list = [];
            foreach ($detail->reward_detail as $key => $value) {
                $item_id = $value->item_id;
                if (isset($value->type) && in_array($value->type, [2, 3, 4, 12])) {//个性商品
                    $data = $mall_products[$item_id] ?? [];
                } elseif (isset($value->type) && $value->type == 6) {//礼物
                    $data = $all_gift[$item_id] ?? [];
                } else {
                    $data = $all_reward_item[$item_id] ?? [];
                }
                $list[] = [
                    'id'      => $value->item_id,
                    'name'    => $data->name ?? '',
                    'picture' => $data->picture ?? '',
                    'number'  => ($value->number ?? 1) * $number,
                    'type'    => $value->type,
                    'weight'  => $value->weight,
                ];
            }
            $return_data = [
                'id'       => $detail->id,
                'name'     => $detail->name,
                'picture'  => $detail->picture,
                'type'     => 1,//道具包
                'number'   => $detail->number * $number,
                'remark'   => $detail->remark,
                'bag_type' => $detail->type,//道具包类型1普通2特殊
                'list'     => $list,
            ];
        } else {
            $detail = $all_reward_item[$id] ?? [];
            $list[] = [
                'id'      => $id,
                'name'    => $detail->name ?? '',
                'picture' => $detail->picture ?? '',
                'number'  => $number,
                'type'    => $detail->type ?? 1,//具体奖励类型，如金币、积分等
            ];
            $return_data = [
                'id'      => $id,
                'name'    => $detail->name ?? '',
                'picture' => $detail->picture ?? '',
                'type'    => 2,//道具
                'number'  => $number,
                'remark'  => $detail->remark ?? '',
                'list'    => $list,
            ];
        }

        return $return_data;
    }

    //items[] = ['id' => 1, 'type' => 1]
    public function getRewardDetailBatch($items)
    {
        $return_data = [];
        foreach ($items as $key => $value) {
            $type = $value['type'] ?? 1;
            $id = $value['id'] ?? 0;
            $re = $this->getRewardDetail($id, $type);
            foreach ($re as $k => $v) {
                $kk = $v['type'].'-'.$v['id'];
                if (isset($return_data[$kk])) {
                    $return_data[$kk] = $v;
                    $return_data[$kk]['number'] = $return_data[$kk]['number'] + $v['number'];
                } else {
                    $return_data[$kk] = $v;
                }
            }
        }

        return array_values($return_data);
    }

    public function getRewardInfo($id, $type)
    {
        if ($type == 1) {
            $detail = app('model_reward')->where('id', $id)->first();

            return [
                'name'    => $detail->name ?? '',
                'picture' => $detail->picture ?? '',
                'number'  => isset($detail->number) && $detail->number > 0 ? $detail->number : 1,
            ];
        } else {
            $detail = app('model_reward_item')->where('id', $id)->first();

            return [
                'name'    => $detail->name ?? '',
                'picture' => $detail->picture ?? '',
                'number'  => 1,
            ];
        }
    }
}
